﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Transactions;
using System.Data.SqlClient;

using Global.Class.Library;
using DataTransferObject;
using DataAccessLayer;
using DataAccessLayer.MetaDataList;
using DataAccessLayer.MetaDataList.ListCustomerTypeDTSTableAdapters;


namespace BusinessLogicLayer
{
    public class ListCustomerTypeBLL : NotifyPropertyChangeObject
    {
        public GlobalEnum.TaskID TaskID { get { return GlobalEnum.TaskID.ListCustomerType; } }

        private UserInformation userOrganization;

        private ListCustomerTypeMaster listCustomerTypeMaster;

        private BindingList<ListCustomerTypeDetail> listCustomerTypeDetailList;



        public ListCustomerTypeBLL()
        {
            try
            {
                if (GlobalVariables.shouldRestoreProcedure) RestoreProcedure();

                userOrganization = new UserInformation();

                listCustomerTypeMaster = new ListCustomerTypeMaster();

                this.listCustomerTypeDetailList = new BindingList<ListCustomerTypeDetail>();

                GlobalDefaultValue.Apply(this);


                this.ListCustomerTypeMaster.PropertyChanged += new PropertyChangedEventHandler(ListCustomerTypeMaster_PropertyChanged);

                this.ListCustomerTypeDetailList.ListChanged += new ListChangedEventHandler(ListCustomerTypeDetailList_ListChanged);

            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        private void ListCustomerTypeMaster_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void ListCustomerTypeDetailList_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }




        #region <Adapter>

        private ListCustomerTypeListingTableAdapter listingTableAdapter;
        protected ListCustomerTypeListingTableAdapter ListingTableAdapter
        {
            get
            {
                if (listingTableAdapter == null) listingTableAdapter = new ListCustomerTypeListingTableAdapter();
                return listingTableAdapter;
            }
        }

        private ListCustomerTypeTableAdapter masterTableAdapter;
        protected ListCustomerTypeTableAdapter MasterTableAdapter
        {
            get
            {
                if (masterTableAdapter == null) masterTableAdapter = new ListCustomerTypeTableAdapter();
                return masterTableAdapter;
            }
        }

        private ListCustomerTypeDetailTableAdapter detailTableAdapter;
        protected ListCustomerTypeDetailTableAdapter DetailTableAdapter
        {
            get
            {
                if (detailTableAdapter == null) detailTableAdapter = new ListCustomerTypeDetailTableAdapter();
                return detailTableAdapter;
            }
        }


        #endregion <Adapter>

        #region <Storage>

        public UserInformation UserOrganization
        {
            get { return this.userOrganization; }
            set { this.userOrganization = value; }
        }

        public ListCustomerTypeDTS.ListCustomerTypeListingDataTable ListCustomerTypeListing()
        {
            return this.ListingTableAdapter.GetData();
        }

        public ListCustomerTypeMaster ListCustomerTypeMaster
        {
            get { return this.listCustomerTypeMaster; }
        }

        public BindingList<ListCustomerTypeDetail> ListCustomerTypeDetailList
        {
            get { return this.listCustomerTypeDetailList; }
        }


        #endregion <Storage>

        #region Properties

        #region <Primary Key>

        public int CustomerTypeID   //Primary Key
        {
            get { return this.ListCustomerTypeMaster.CustomerTypeID; }
            private set
            {
                if (this.ListCustomerTypeMaster.CustomerTypeID != value)
                {
                    this.StopTracking();

                    this.ListCustomerTypeMaster.CustomerTypeID = value;

                    this.ListCustomerTypeGetMaster();
                    this.ListCustomerTypeGetDetail();

                    this.StartTracking();
                    this.Reset();
                }

            }
        }

        #endregion <Primary Key>

        private void ListCustomerTypeGetMaster()
        {
            if (this.CustomerTypeID > 0)
            {
                ListCustomerTypeDTS.ListCustomerTypeDataTable masterDataTable = this.MasterTableAdapter.GetData(this.CustomerTypeID);

                if (masterDataTable.Count > 0)
                {
                    this.ListCustomerTypeMaster.StopTracking();

                    this.ListCustomerTypeMaster.EntryDate = masterDataTable[0].EntryDate;

                    this.ListCustomerTypeMaster.AncestorID = masterDataTable[0].AncestorID;
                    this.ListCustomerTypeMaster.ColumnReportID = masterDataTable[0].ColumnReportID;

                    this.ListCustomerTypeMaster.Description = masterDataTable[0].Description;
                    this.ListCustomerTypeMaster.Other = masterDataTable[0].Other;

                    this.ListCustomerTypeMaster.StartTracking();

                    this.ListCustomerTypeMaster.Reset();

                    this.UserOrganization.UserID = masterDataTable[0].UserID;
                    this.UserOrganization.UserOrganizationID = masterDataTable[0].UserOrganizationID;
                }
                else throw new System.ArgumentException("Insufficient get data");
            }
            else
            {
                GlobalDefaultValue.Apply(this.ListCustomerTypeMaster);
                this.ListCustomerTypeMaster.EntryDate = DateTime.Today;
                this.ListCustomerTypeMaster.Reset();
            }
        }


        private void ListCustomerTypeGetDetail()
        {
            this.listCustomerTypeDetailList.RaiseListChangedEvents = false;
            this.listCustomerTypeDetailList.Clear();
            if (this.CustomerTypeID >= 0)
            {

                ListCustomerTypeDTS.ListCustomerTypeDetailDataTable detailDataTable = this.DetailTableAdapter.GetData(this.CustomerTypeID);

                if (detailDataTable.Count > 0)
                {
                    foreach (ListCustomerTypeDTS.ListCustomerTypeDetailRow detailRow in detailDataTable.Rows)
                    {
                        this.listCustomerTypeDetailList.Add(new ListCustomerTypeDetail(detailRow.CommonID, detailRow.CommonValue, detailRow.Remarks));
                    }
                }
            }
            this.listCustomerTypeDetailList.RaiseListChangedEvents = true;
            this.listCustomerTypeDetailList.ResetBindings();
        }

        #endregion Properties





        #region Object Permission

        public override bool IsValid
        {
            get
            {
                List<ListCustomerTypeDetail> inValidListCustomerTypeDetail = this.ListCustomerTypeDetailList.Where(listCustomerTypeDetail => !listCustomerTypeDetail.IsValid).ToList();
                return this.ListCustomerTypeMaster.IsValid && inValidListCustomerTypeDetail.Count == 0;
            }
        }

        public bool ReadOnly
        {
            get
            {
                try
                {
                    return GlobalUserPermission.GetUserReadOnly(GlobalVariables.GlobalUserInformation.UserID, this.TaskID);
                }
                catch
                {
                    return true;
                }
            }
        }

        public bool Editable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, this.TaskID, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListCustomerTypeEditable", this.CustomerTypeID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Verifiable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.ListCustomerTypeVerifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListCustomerTypeEditable", this.CustomerTypeID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Unverifiable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.ListCustomerTypeUnverifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListCustomerTypeEditable", this.CustomerTypeID);
                }
                catch
                {
                    return false;
                }
            }
        }


        #endregion Object Permission






        public void Fill(int customerTypeID)
        {
            if (this.CustomerTypeID == customerTypeID) this.CustomerTypeID = -1; //Enforce to reload
            this.CustomerTypeID = customerTypeID;
        }

        public void New()
        {
            if (this.CustomerTypeID == 0) this.CustomerTypeID = -1;
            this.CustomerTypeID = 0;
        }

        public void Edit()
        {

        }

        #region Save & Delete Method


        public bool Save()
        {
            int customerTypeID = 0;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient save", "Save validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (this.ReadOnly) throw new System.ArgumentException("Insufficient save", "Uneditable");

                    if (!this.SaveMaster(ref customerTypeID)) throw new System.ArgumentException("Insufficient save", "Save master");

                    if (!this.SaveDetail(customerTypeID)) throw new System.ArgumentException("Insufficient save", "Save detail");
    
                    transactionScope.Complete();
                }

                SQLDatabase.ExecuteNonQuery("ListCustomerTypeUpdateHierarchyLevel", CommandType.StoredProcedure, "AncestorID", this.listCustomerTypeMaster.AncestorID);

                this.Fill(customerTypeID);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        public bool Delete()
        {
            if (this.listCustomerTypeMaster.CustomerTypeID <= 0) return false;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient delete", "Delete validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (!this.Editable) throw new System.ArgumentException("Insufficient delete", "Uneditable");

                    if (!this.SaveUndo(this.listCustomerTypeMaster.CustomerTypeID)) throw new System.ArgumentException("Insufficient delete", "Delete detail");

                    if (this.MasterTableAdapter.Delete(this.listCustomerTypeMaster.CustomerTypeID) != 1) throw new System.ArgumentException("Insufficient delete", "Delete master");

                    transactionScope.Complete();
                }
                this.Fill(0);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        private bool SaveValidate()
        {
            ExceptionTable exceptionTable = new ExceptionTable(new string[2, 2] { { "ExceptionCategory", "System.String" }, { "ExceptionDescription", "System.String" } });

            this.UserOrganization = GlobalUserPermission.GetUserInformation(this.UserOrganization.UserID, this.ListCustomerTypeMaster.EntryDate);

            if (this.UserOrganization.UserID <= 0 || this.UserOrganization.UserOrganizationID <= 0) exceptionTable.AddException(new string[] { GlobalVariables.stringFieldRequired, "User information" });

            if (exceptionTable.Table.Rows.Count <= 0 && this.IsValid) return true; else throw new CustomException("Save validate", exceptionTable.Table);
        }


        private bool SaveMaster(ref int customerTypeID)
        {
            ListCustomerTypeDTS.ListCustomerTypeDataTable masterDataTable;
            ListCustomerTypeDTS.ListCustomerTypeRow masterRow;

            if (this.listCustomerTypeMaster.CustomerTypeID <= 0) //Add
            {
                masterDataTable = new ListCustomerTypeDTS.ListCustomerTypeDataTable();
                masterRow = masterDataTable.NewListCustomerTypeRow();
            }
            else //Edit
            {
                if (!this.SaveUndo(listCustomerTypeMaster.CustomerTypeID)) throw new System.ArgumentException("Insufficient save", "Save undo");
                masterDataTable = this.MasterTableAdapter.GetData(listCustomerTypeMaster.CustomerTypeID);
                if (masterDataTable.Count > 0) masterRow = masterDataTable[0]; else throw new System.ArgumentException("Insufficient save", "Get for edit");
            }

            masterRow.EntryDate = this.listCustomerTypeMaster.EntryDate;

            masterRow.AncestorID = this.listCustomerTypeMaster.AncestorID;
            masterRow.HierarchyLevel = 0;
            masterRow.HierarchyOrder = "";

            masterRow.ColumnReportID = this.listCustomerTypeMaster.ColumnReportID;

            masterRow.Description = this.listCustomerTypeMaster.Description;
            masterRow.Other = this.listCustomerTypeMaster.Other;

            masterRow.UserID = this.UserOrganization.UserID;
            masterRow.UserOrganizationID = this.UserOrganization.UserOrganizationID;

            if (this.listCustomerTypeMaster.CustomerTypeID <= 0) masterDataTable.AddListCustomerTypeRow(masterRow);

            int rowsAffected = this.MasterTableAdapter.Update(masterRow);

            customerTypeID = masterRow.CustomerTypeID;

            return rowsAffected == 1;

        }


        private bool SaveDetail(int customerTypeID)
        {
            int serialID = 0; int rowsAffected = 0;


            #region <Save collection>

            serialID = 0;

            ListCustomerTypeDTS.ListCustomerTypeDetailDataTable detailDataTable = new ListCustomerTypeDTS.ListCustomerTypeDetailDataTable();

            foreach (ListCustomerTypeDetail listCustomerTypeDetail in this.ListCustomerTypeDetailList)
            {
                ListCustomerTypeDTS.ListCustomerTypeDetailRow detailRow = detailDataTable.NewListCustomerTypeDetailRow();

                detailRow.CustomerTypeID = customerTypeID;
                detailRow.SerialID = ++serialID;

                detailRow.CommonID = listCustomerTypeDetail.CommonID;
                detailRow.CommonValue = listCustomerTypeDetail.CommonValue;

                detailRow.Remarks = listCustomerTypeDetail.Remarks;

                detailDataTable.AddListCustomerTypeDetailRow(detailRow);
            }

            rowsAffected = this.DetailTableAdapter.Update(detailDataTable);
            if (rowsAffected != this.listCustomerTypeDetailList.Count) throw new System.ArgumentException("Insufficient save", "Save detail");


            #endregion <Save collection>


            return true;
        }


        private bool SaveUndo(int customerTypeID)
        {
            this.DetailTableAdapter.Delete(customerTypeID);

            return true;
        }



        #endregion



        private void RestoreProcedure()
        {
            string queryString;
            string[] queryArray;



            queryString = "     " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, Description, AncestorID, Other, EntryDate " + "\r\n";
            queryString = queryString + "       FROM        ListCustomerType " + "\r\n";
            queryString = queryString + "       ORDER BY    Description " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeListing", queryString);



            queryString = "     @CustomerTypeID Int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, Description, AncestorID, HierarchyLevel, HierarchyOrder, ColumnReportID, Other, EntryDate, UserID, UserOrganizationID " + "\r\n";
            queryString = queryString + "       FROM        ListCustomerType " + "\r\n";
            queryString = queryString + "       WHERE       CustomerTypeID = @CustomerTypeID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeSelect", queryString);


            queryString = "     @Description nvarchar(100),	@AncestorID int, @HierarchyLevel int, @HierarchyOrder nvarchar(50), @ColumnReportID int, @Other nvarchar(100), @EntryDate datetime, @UserID int, @UserOrganizationID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListCustomerType (Description, AncestorID, HierarchyLevel, HierarchyOrder, ColumnReportID, Other, EntryDate, UserID, UserOrganizationID) VALUES (@Description, @AncestorID, @HierarchyLevel, @HierarchyOrder, @ColumnReportID, @Other, @EntryDate, @UserID, @UserOrganizationID) " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, Description, AncestorID, HierarchyLevel, HierarchyOrder, ColumnReportID, Other, EntryDate, UserID, UserOrganizationID FROM ListCustomerType WHERE CustomerTypeID = SCOPE_IDENTITY() " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeInsert", queryString);


            queryString = "     @CustomerTypeID int, @Description nvarchar(100), @AncestorID int, @HierarchyLevel int, @HierarchyOrder nvarchar(50), @ColumnReportID int, @Other nvarchar(100), @EntryDate datetime, @UserID int, @UserOrganizationID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListCustomerType SET Description = @Description, AncestorID = @AncestorID, HierarchyLevel = @HierarchyLevel, HierarchyOrder = @HierarchyOrder, ColumnReportID = @ColumnReportID, Other = @Other, EntryDate = @EntryDate, UserID = @UserID, UserOrganizationID = @UserOrganizationID WHERE CustomerTypeID = @CustomerTypeID " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, Description, AncestorID, HierarchyLevel, HierarchyOrder, ColumnReportID, Other, EntryDate, UserID, UserOrganizationID FROM ListCustomerType WHERE CustomerTypeID = @CustomerTypeID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeUpdate", queryString);


            queryString = " @CustomerTypeID int ";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListCustomerType WHERE CustomerTypeID = @CustomerTypeID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListCustomerTypeDelete", queryString);






            queryString = " @CustomerTypeID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, SerialID, CommonID, CommonValue, Remarks " + "\r\n";
            queryString = queryString + "       FROM        ListCustomerTypeDetail " + "\r\n";
            queryString = queryString + "       WHERE       CustomerTypeID = @CustomerTypeID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeDetailSelect", queryString);


            queryString = " @CustomerTypeID int, @SerialID int,	@CommonID int, @CommonValue float, @Remarks nvarchar(100) " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListCustomerTypeDetail (CustomerTypeID, SerialID, CommonID, CommonValue, Remarks) VALUES (@CustomerTypeID, @SerialID, @CommonID, @CommonValue, @Remarks) " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, SerialID, CommonID, CommonValue, Remarks FROM ListCustomerTypeDetail WHERE (CustomerTypeID = @CustomerTypeID) AND (SerialID = @SerialID) " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeDetailInsert", queryString);



            queryString = " @CustomerTypeID int, @SerialID int,	@CommonID int, @CommonValue float, @Remarks nvarchar(100) " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListCustomerTypeDetail SET CommonID = @CommonID, CommonValue = @CommonValue, Remarks = @Remarks WHERE CustomerTypeID = @CustomerTypeID AND SerialID = @SerialID " + "\r\n";
            queryString = queryString + "       SELECT      CustomerTypeID, SerialID, CommonID, CommonValue, Remarks FROM ListCustomerTypeDetail WHERE CustomerTypeID = @CustomerTypeID AND SerialID = @SerialID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeDetailUpdate", queryString);



            queryString = " @CustomerTypeID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListCustomerTypeDetail WHERE CustomerTypeID = @CustomerTypeID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListCustomerTypeDetailDelete", queryString);


            queryString = " @AncestorID Int ";
            queryString = queryString + " WITH ENCRYPTION ";
            queryString = queryString + " AS ";

            queryString = queryString + "   DECLARE @AncestorHierarchyOrder NVarchar(30), @AncestorHierarchyLevel Int  ";
            queryString = queryString + "   DECLARE @Cursor_Rows Int, @SerialNo Int ";

            queryString = queryString + "   SET @AncestorHierarchyOrder = N'' ";
            queryString = queryString + "   SET @AncestorHierarchyLevel = 0 ";
            queryString = queryString + "   SET @SerialNo = 0 ";
            queryString = queryString + "   SET @Cursor_Rows = 0 ";

            queryString = queryString + "   IF @AncestorID <> 0 ";
            queryString = queryString + "   BEGIN ";

            queryString = queryString + "       DECLARE Ancestor_Cursor CURSOR LOCAL FOR ";
            queryString = queryString + "       SELECT TOP 1 HierarchyOrder, HierarchyLevel FROM ListCustomerType ";
            queryString = queryString + "       WHERE CustomerTypeID = @AncestorID ";

            queryString = queryString + "       OPEN Ancestor_Cursor ";

            queryString = queryString + "       FETCH NEXT FROM Ancestor_Cursor INTO @AncestorHierarchyOrder, @AncestorHierarchyLevel ";

            queryString = queryString + "       CLOSE Ancestor_Cursor ";
            queryString = queryString + "       DEALLOCATE Ancestor_Cursor ";


            queryString = queryString + "   END ";

            queryString = queryString + "   DECLARE @CustomerTypeID Int ";

            queryString = queryString + "   DECLARE CustomerType_Cursor CURSOR LOCAL SCROLL FOR ";
            queryString = queryString + "   SELECT CustomerTypeID FROM ListCustomerType ";
            queryString = queryString + "   WHERE AncestorID = @AncestorID ORDER BY Description ";
            queryString = queryString + "   FOR UPDATE ";

            queryString = queryString + "   OPEN CustomerType_Cursor ";

            queryString = queryString + "   FETCH LAST FROM CustomerType_Cursor INTO @CustomerTypeID ";
            queryString = queryString + "   IF @@FETCH_STATUS = 0 ";
            queryString = queryString + "   BEGIN ";
            queryString = queryString + "       SET @Cursor_Rows = @@CURSOR_ROWS ";
            queryString = queryString + "       FETCH FIRST FROM CustomerType_Cursor INTO @CustomerTypeID ";
            queryString = queryString + "   END ";

            queryString = queryString + "   WHILE @@FETCH_STATUS = 0";
            queryString = queryString + "   BEGIN";

            queryString = queryString + "       SET @SerialNo = @SerialNo + 1 ";

            queryString = queryString + "       UPDATE ListCustomerType SET HierarchyOrder = @AncestorHierarchyOrder +  REPLICATE('0', DATALENGTH(CONVERT (NVarchar(30), @Cursor_Rows)) - DATALENGTH(CONVERT (NVarchar(30), @SerialNo))) + CONVERT (NVarchar(30), @SerialNo), HierarchyLevel = @AncestorHierarchyLevel + 1 ";
            queryString = queryString + "       WHERE CURRENT OF CustomerType_Cursor ";

            queryString = queryString + "       EXECUTE ListCustomerTypeUpdateHierarchyLevel @AncestorID = @CustomerTypeID ";

            queryString = queryString + "       FETCH NEXT FROM CustomerType_Cursor INTO @CustomerTypeID ";

            queryString = queryString + "   END ";

            queryString = queryString + "   CLOSE CustomerType_Cursor ";
            queryString = queryString + "   DEALLOCATE CustomerType_Cursor ";

            SQLDatabase.CreateStoredProcedure("ListCustomerTypeUpdateHierarchyLevel", queryString);





            /// <summary>
            /// Check for editable
            /// </summary>
            queryArray = new string[4];//@InMarketID Int, @InMarketDate DateTime
            queryArray[0] = "   SELECT      TOP 1 CustomerTypeID FROM ListCustomerType WHERE AncestorID = @FindIdentityID " ;
            queryArray[1] = "   SELECT      TOP 1 CustomerTypeID FROM ListCustomerName WHERE CustomerTypeID = @FindIdentityID " ;
            queryArray[2] = "   SELECT      TOP 1 CustomerTypeID FROM QuotaDetail WHERE CustomerTypeID = @FindIdentityID " ;
            queryArray[3] = "   SELECT      TOP 1 CustomerTypeID FROM InMarketMaster WHERE CustomerTypeID = @FindIdentityID " ;

            SQLDatabase.CreateProcedureToCheckExisting("ListCustomerTypeEditable", queryArray);

        }



    }
}
